package cn.py.boot_lua.handler.impl;

import cn.py.boot_lua.handler.admin.RequestTask;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class ImageCaptionServiceImpl {
    @Async("taskExecutor")
    public void submitAsync(RequestTask task, Runnable callback) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(task.getRequestData());
            String taskId = task.getRequestId();
            String uid = jsonObject.getString("uid");
            String apiKey = jsonObject.getString("apiKey");
            log.info("请求图配文的参数为: {}",task.getRequestData());
            processDataAsync(task.getRequestData(), taskId, uid, apiKey);
        }catch (Exception e) {
            log.error("任务处理过程中发生未知错误: " + task, e);
        } finally {
            if (callback != null) {
                callback.run();
            }
        }
    }

    private void processDataAsync(String requestData, String taskId, String uid, String apiKey) {
        try {
            Thread.sleep(10 * 1000);
            log.info("requestData: " + requestData);
            log.info("taskId: " + taskId);
            log.info("uid: " + uid);
            log.info("apiKey: " + apiKey);
            int sun = Integer.parseInt(apiKey) + Integer.parseInt(uid);
            log.info("sun 图配文结果为: " + sun);
            log.info("------------------------------------结束--------------------------------------------");
        }catch (NumberFormatException e) {
            throw new NumberFormatException("参数不合法！");
        } catch (ArithmeticException e) {
            throw new ArithmeticException("错误：除数不能为零！");
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

}
